package com.kzw.oa.action.system;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import nl.captcha.Captcha;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;

import com.kzw.core.util.AppUtil;
import com.kzw.core.util.StringUtil;
import com.kzw.core.web.action.BaseAction;
import com.kzw.oa.model.system.AppUser;
import com.kzw.oa.model.system.SysConfig;
import com.kzw.oa.model.system.SystemLog;
import com.kzw.oa.service.system.AppUserService;
import com.kzw.oa.service.system.SysConfigService;
import com.kzw.oa.service.system.SystemLogService;

public class LoginAction extends BaseAction {
	private AppUser user;
	private String username;
	private String password;
	private String checkCode;// 验证码

	// must be same to app-security.xml
	private String key = "RememberAppUser";

	// private String rememberMe;//自动登录
	@Resource
	private AppUserService userService;
	@Resource
	private SysConfigService sysConfigService;
	@Resource(name = "authenticationManager")
	private AuthenticationManager authenticationManager = null;
	@Autowired
	private SystemLogService logService;

	/**
	 * jsp登录
	 */
	public String login() {
		AppUser user = userService.findByUserName(username);
		if (user == null) {
			jsonString = "{\"success\":false,\"msg\":\"该用户账号不存在!\"}";
			return SUCCESS;
		}
		if (user.getStatus() != 1) {
			jsonString = "{\"success\":false,\"msg\":\"账号已经被禁用!\"}";
			return SUCCESS;
		}
		// 取得验证码配置
		SysConfig codeConfig = sysConfigService.findByKey("codeConfig");

		// 判断密码及用户名是否一致
		String newPassword = StringUtil.encryptSha256(password);
		// 密码是否一致
		if (!user.getPassword().equals(newPassword)) {
			jsonString = "{\"success\":false,\"msg\":\"密码不正确\"}";
			return SUCCESS;
		}

		// 检查验证码
		Captcha captcha = (Captcha) getSession().getAttribute(Captcha.NAME);
		// 判断是否需要验证码验证
		if (codeConfig != null
				&& codeConfig.getDataValue().equals(SysConfig.CODE_OPEN)) {
			// 验证码验证
			if (captcha != null && !captcha.isCorrect(checkCode)) {
				jsonString = "{\"success\":false,\"msg\":\"验证码不正确\"}";
				return SUCCESS;
			}
		}

		// 验证ip段，并记录谁使用非法IP登陆
		try {
			String ipValid = (String) AppUtil.getSysConfig().get("ipValid");
			if (ipValid != null && Boolean.parseBoolean(ipValid)) {
				String ipPattern = (String) AppUtil.getSysConfig().get(
						"ipPattern");
				if (ipPattern != null) {
					String ip = getRequest().getRemoteAddr();
					if (!ip.matches(ipPattern)) {
						SystemLog log = new SystemLog();
						log.setUserId(user.getUserId());
						log.setUsername(user.getUsername());
						log.setExeOperation("IP非法, " + ip);
						log.setCreatetime(new Date());
						logService.save(log);
						jsonString = "{\"success\":false,\"msg\":\"IP段非法，此用户被记录!\"}";
						return SUCCESS;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
					username, password);
			SecurityContext securityContext = SecurityContextHolder
					.getContext();
			securityContext.setAuthentication(authenticationManager
					.authenticate(authRequest));
			SecurityContextHolder.setContext(securityContext);
			getSession().setAttribute(
							UsernamePasswordAuthenticationFilter.SPRING_SECURITY_LAST_USERNAME_KEY,
							username);

			String rememberMe = getRequest().getParameter(
					"_spring_security_remember_me");
			if (rememberMe != null && rememberMe.equals("on")) {
				// 加入cookie
				long tokenValiditySeconds = 1209600; // 14 days
				long tokenExpiryTime = System.currentTimeMillis()
						+ (tokenValiditySeconds * 1000);
				String signatureValue = DigestUtils.md5Hex(username + ":"
						+ tokenExpiryTime + ":" + user.getPassword() + ":"
						+ key);
				String tokenValue = username + ":" + tokenExpiryTime + ":"
						+ signatureValue;
				String tokenValueBase64 = new String(
						Base64.encodeBase64(tokenValue.getBytes()));
				getResponse().addCookie(
						makeValidCookie(tokenExpiryTime, tokenValueBase64));
			}

		} catch (Exception ex) {
			ex.printStackTrace();
			jsonString = "{\"success\":false,\"msg\":\"" + ex.getCause()
					+ "\"}";
			return SUCCESS;
		}

		return SUCCESS;
	}

	// add Cookie
	protected Cookie makeValidCookie(long expiryTime, String tokenValueBase64) {
		HttpServletRequest request = getRequest();
		Cookie cookie = new Cookie(
				TokenBasedRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
				tokenValueBase64);
		cookie.setMaxAge(60 * 60 * 24 * 365 * 5); // 5 years
		cookie.setPath(org.springframework.util.StringUtils.hasLength(request
				.getContextPath()) ? request.getContextPath() : "/");
		return cookie;
	}

	public AppUser getUser() {
		return user;
	}

	public void setUser(AppUser user) {
		this.user = user;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getCheckCode() {
		return checkCode;
	}

	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}

	/**
	 * 验证码 <no use>
	 * 
	 * @return
	 */
	public String validateCaptcha() {
		// 定义验证信息
		StringBuffer msg = new StringBuffer("{msg:'");
		// 取得验证码配置
		SysConfig codeConfig = sysConfigService.findByKey("codeConfig");

		// 取得验证码
		Captcha captcha = (Captcha) getSession().getAttribute(Captcha.NAME);

		// 判断是否需要验证码验证
		if (codeConfig != null
				&& codeConfig.getDataValue().equals(SysConfig.CODE_OPEN)) {
			if (captcha == null) {
				msg.append("请刷新验证码再登录.'");
			} else {
				// 验证码验证
				if (captcha.isCorrect(checkCode)) {
					// login = dyPwdCheck(msg, login);
					setJsonString("{success:true}");
				} else {
					msg.append("验证码不正确.'");
					msg.append(",failure:true}");
					setJsonString(msg.toString());
				}
			}
		} else {
			// 此处不需要验证码验证
			// login = dyPwdCheck(msg, login);
			setJsonString("{success:true}");
		}
		return SUCCESS;
	}

}
